<?php
namespace app\dao;

/**
 * @desc 采购入库明细表操作类
 * @author liaojianwen
 * @date 2016-12-14
 */

use yii\db\Query;
use app\dao\BaseDAO;
use app\enum\EnumOther;
use yii\base\Object;

class PurchaseDetailDAO extends BaseDAO
{
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2016-12-14
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'purchase_detail';
		$this->_pKey ='purchase_det_id';
	}
	
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%purchase_detail}}';
	}
	
	
	/**
	 * @desc 根据id 获取采购入库单明细
	 * @param $id 采购入库单id
	 * @author liaojianwen
	 * @date 2016-12-14
	 */
	public function getPurchaseDet($id)
	{
		$selects = "purchase_det_id,purchase_id,goods_id,d.quantity,d.remark,p.product_name,product_sn,p.quantity product_quantity,base_price,
				d.quantity_unit,d.price,d.amount,d.return_quantity,d.minus_quantity,d.procurement_det_id,base_quantity,base_unit,u.unit_name base_name,second_quantity,second_unit,second_relation,p.unit_content";
		$conditions ="d.purchase_id = :id and d.delete_flag = :flag";
		$params = [
				':id'=>$id,
				':flag'=>EnumOther::NO_DELETE,
		];
		$query = new Query();
		$result = $query->select($selects)
		->from("$this->_table d")
		->leftJoin("product p",'d.goods_id = p.product_id')
		->leftJoin("unit u","u.unit_id = d.base_unit")
		->where($conditions,$params)
		->all();
		foreach ($result as &$res){
			$res_units = ProductUnitDAO::getInstance()->getUnits($res['goods_id'] );
			$res['product_unit'] = $res_units;
		}
		return $result;
	
	}
	
	
	/**
	 * @desc 确认采购入库明细已退到数量，确认是否完成
	 * @param $proid 采购订单id
	 * @param  [ 'purchase_return_no' => string '20161219090249' (length=14)
	 *			 'product_id' => string '8' (length=1)
	 *			 'quantity' => string '25' (length=2)
	 *			 'purchase_return_type' => string '1' (length=1)
	 *			 'purchase_return_det_id' => string '10' (length=2)
	 *			 'warehouse_id' => string '1' (length=1)
	 *			 'purchase_det_id' => string '6' (length=1)
	 *			 'minus_quantity' => string '25' (length=2)
	 *			 'return_quantity' => string '25' (length=2)
	 *		  ]
	 * @author liaojianwen
	 * @date 2017-04-28
	 */
	public function updateFinish($proid, $det)
	{
		$pro_det = $this->findByAttributes ( "minus_quantity,return_quantity,base_quantity,finish_flag", "purchase_det_id =:detid", [
				':detid' => $det ['purchase_det_id']
		] );
		$total_quantity = $pro_det ['return_quantity'] + $det ['base_quantity'];
		if ($total_quantity > $pro_det ['base_quantity']) {
			//现在的值加上原来单据上的超过了未收的数量
			$result ['Ack'] = 'error';
			$result ['msg'] = 'total quantity is lt return_quantity';
			return $result;
		} else if ($total_quantity == $pro_det ['base_quantity']) {
			//现在数量加上单据上的数量 刚好等于未收数量//标记完成
			$detail_flag = $this->iupdate ( [
					'finish_flag' => EnumOther::FINISHED
			], "purchase_det_id=:pid", [
					':pid' => $det ['purchase_det_id']
			] );
			if (! $detail_flag) {
				$result ['Ack'] = 'error';
				$result ['msg'] = 'update detail finish_flag fail';
				return $result;
			}
		}
		$condition = "purchase_det_id =:detid";
		$params = [
				':detid' => $det ['purchase_det_id']
		];
		$received_quantity = $this->updateAllCounters ( [
				"return_quantity" => $det ['base_quantity'],
				"minus_quantity"=> -$det['base_quantity'],//未收数量变更为原来单据数量- 已收数量
		], $condition, $params );
		if (! $received_quantity) {
			$result ['Ack'] = 'error';
			$result ['msg'] = 'update return quantity fail';
			return $result;
		}
	
		//查找是否还有未完成的明细，如果有就不用给head 更新finish_flag,如果没有就给head 的finish_flag 打上完成
		$exit_unfinish = $this->findByAttributes ( "purchase_det_id", "purchase_id=:pid and finish_flag=:flag and delete_flag =:dflag", [
				':pid' => $proid,
				':flag' => EnumOther::NO_FINISHED,
				':dflag' => EnumOther::NO_DELETE,
		] );
		if (!$exit_unfinish) {
			$head_flag = PurchaseDAO::getInstance ()->iupdate ( [
					'finish_flag' => EnumOther::FINISHED
			], "purchase_id=:pid", [
					':pid' => $proid
			] );
			if(empty($head_flag)) {
				$result ['Ack'] = 'error';
				$result ['msg'] = 'update head finish_flag fail';
				return $result;
			}
		}
		return [
				'Ack' => 'success'
		];
	}
	
	/**
	 * @desc 获取特定商品入库情况
	 * @author liaojianwen
	 * @date 2018-04-13
	 */
	public function getSpecialIn($condition, $goods_id)
	{
		$selections = ['d.goods_id','sum(base_quantity) quantity','sum(base_price) price','ROUND(sum(base_quantity)*sum(base_price),2) amount','g.product_name','u.unit_name'];
		$conditions ="d.goods_id = :id and d.delete_flag = :flag";
		$params = [
				':id'=>$goods_id,
				':flag'=>EnumOther::NO_DELETE,
		];
		
		$query = new Query();
		
		 $query->select($selections)
			->from("$this->_table d")
			->innerJoin("purchase p","p.purchase_id = d.purchase_id")
			->innerJoin("product_extend e","e.product_id = d.goods_id and goods_type = ".EnumOther::BASE_GOODS)
			->innerJoin("product g","g.product_id = d.goods_id")
			->innerJoin("unit u","g.quantity_unit = u.unit_id")
			->where($conditions, $params);
		
		if(isset($condition['starTime']) && !empty($condition['starTime'])){
			$query->andwhere(['between','p.purchase_date',strtotime($condition['starTime']), strtotime($condition['endTime'])]);
		}
		
		$result= $query->groupBy("d.goods_id")->all();
		return $result;
		
	}
	
}